import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common import WebDriverException, NoSuchWindowException


class Base:
    # 初始化,打开浏览器类型
    def __init__(self, browser):
        # 打开浏览器,设置driver
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        else:
            print('不支持该浏览器')
            self.driver = None

    def get(self, url):
        # 请求目标网址
        try:
            self.driver.get(url)
        except WebDriverException:
            print('网址输入错误')

    # 刷新
    def refresh(self):
        self.driver.refresh()

    # 后退
    def back(self):
        self.driver.back()

    # 前进
    def forward(self):
        self.driver.forward()

    def find_element(self, locator):
        # locator = (By.xxx,value)
        # 定位元素
        try:
            ele = self.driver.find_element(*locator) # 拆包(因为locator是元组)
            print(ele.get_attribute('outerHTML'))
            return ele
        except Exception as e:
            print('元素定位失败')

    def click(self, locator):
        ele = self.find_element(locator)
        if ele is not None:
            ele.click()
        else:
            print('元素定位失败')

    # get_attribute 属性
    def get_attribute(self, locator, attribute):
        element = self.find_element(locator)
        if element is not None:
            attr = element.get_attribute(attribute)
        else:
            print('元素定位失败')

    # 输入 send_keys
    def send_keys(self, locator, text):
        element = self.find_element(locator)
        if element is not None:
            element.send_keys(text) # 不需要返回
        else:
            print('元素定位失败')

    # 浏览器退出
    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com')
    base.find_element((By.ID, 'kw'))
    base.click((By.ID, 'su'))
    time.sleep(3)
    base.refresh()
    time.sleep(2)
    base.back()
    time.sleep(2)
    base.forward()
    time.sleep(2)
    base.get_attribute((By.ID, 'kw'), 'outerHTML')
    base.quit()
